<html>

<head>
    <title>websocket client</title>
</head>

<body>
<textarea id="msg" style="width: 100%; height: 200px"></textarea>
<button type="button" id="send">发送消息</button>
<script>
    //连接验证token，写成debug可以绕过验证
    var token = 'debug';
    //websocket服务端地址
    var server = 'ws://127.0.0.1:8888/ws/price?token=' + token;

    //创建ws对象
    ws = new WebSocket(server);

    //连接成功事件
    ws.onopen = function (event) {
        console.log('连接成功');
        //发送订阅命令
        ws.send('{"cmd":"topics", "data":"SI,CL"}');

        //接收服务端消息事件
        ws.onmessage = function (event) {
            console.log('服务端消息：' + event.data);
        };
        //连接关闭事件
        ws.onclose = function (event) {
            ws = null;
            console.log('连接已断开');
        };
        document.getElementById("send").onclick = function () {
            var msg = document.getElementById("msg").value;
            if (msg==='') {
                alert('消息内容不能为空');
                return false
            }
            //发送消息给服务端
            ws.send(msg);
            console.log('发送消息 '+msg);
        };
    };

    //错误事件
    ws.onerror = function (event) {
        ws = null;
        console.log('连接失败');
    };
</script>
</body>

</html>